package com.leyou.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.leyou.constant.SmsConstants;
import com.leyou.exception.LyException;
import com.leyou.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class SendMessageHelper implements SMS {
    //配置文件

    @Autowired
    private IAcsClient iAcsClient;

    @Autowired
    private SmsProperties prop;

    @Override
    public void sendMessage(String phone, String code) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(prop.getDomain());
        request.setVersion(prop.getVersion());
        request.setAction(prop.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_REGION_ID, prop.getRegionID());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME, prop.getSignName());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE, prop.getVerifyCodeTemplate());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{code: " + code + "}");
        try {
            CommonResponse response = iAcsClient.getCommonResponse(request);
            String data = response.getData();
            Map<String, String> map = JsonUtils.toMap(data, String.class, String.class);
            String responseCode = map.get(SmsConstants.SMS_RESPONSE_KEY_CODE);
            if (StringUtils.equals(responseCode, SmsConstants.OK)) {
                log.info("短信发送成功，手机号：" + phone + "\n短信验证码: " + code);
                return;
            }
            log.error("阿里云短信发送失败，代码问题", map.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE));
//            throw new LyException(501, "阿里云短信发送失败");
        } catch (ClientException e) {
            log.error("阿里云短信发送失败,微服务异常", e.getMessage());
            throw new LyException(501, "阿里云短信发送失败");
        }
    }
}
